﻿using System.Linq;
using ReAnimation.Domain;
using ReAnimation.MVP.Models.Interfaces;
using ReAnimation.MVP.ViewInterfaces;

namespace ReAnimation.MVP.Presenters
{
    public class LinkingDialogPresenter: BasePresenter<ILinkingDialogView>
    {
        private IMainModel _mainModel;
        private IMainPresentationModel _mainPresentationModel;

        public LinkingDialogPresenter(IMainModel mainModel, IMainPresentationModel mainPresentationModel)
        {
            _mainModel = mainModel;
            _mainPresentationModel = mainPresentationModel;
        }

        protected override void InitView()
        {
            View.LinkTypeSelected += View_LinkTypeSelected;
            Link currentLink = GetCurrentLink();
            if (currentLink != null)
                View.SelectedLinkType = currentLink.LinkType;
        }

        void View_LinkTypeSelected(object sender, System.EventArgs e)
        {
            Link currentLink = GetCurrentLink();

            if (currentLink == null)
            {
                _mainModel.CurrentMolecule.AddLink(new Link
                {
                    Atom1 = _mainPresentationModel.CurrentlySelectedForLinkingAtoms.Value1,
                    Atom2 = _mainPresentationModel.CurrentlySelectedForLinkingAtoms.Value2,
                    LinkType = View.SelectedLinkType
                });
            }
            else
                currentLink.LinkType = View.SelectedLinkType;

            _mainModel.CurrentMoleculeStructureWasModified();
        }

        private Link GetCurrentLink()
        {
            var links = from link in _mainModel.CurrentMolecule.Links
                        where (link.Atom1 == _mainPresentationModel.CurrentlySelectedForLinkingAtoms.Value1 &&
                               link.Atom2 == _mainPresentationModel.CurrentlySelectedForLinkingAtoms.Value2) ||
                              (link.Atom1 == _mainPresentationModel.CurrentlySelectedForLinkingAtoms.Value2 &&
                               link.Atom2 == _mainPresentationModel.CurrentlySelectedForLinkingAtoms.Value1)
                        select link;

            return links.FirstOrDefault();
        }
    }
}
